package com.hao.vertx.web.datasource;


import com.hao.vertx.core.util.VertxHolder;
import io.vertx.core.Vertx;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.SharedData;
import io.vertx.core.tracing.TracingPolicy;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.jdbcclient.impl.JDBCPoolImpl;
import io.vertx.sqlclient.impl.tracing.QueryTracer;

public class JDBCPoolHolder {

    private static JDBCPool jdbcPool;

    public static JDBCPool getJdbcPool() {
        return jdbcPool;
    }

    public static void init() {
        Vertx vertx = VertxHolder.getVertxInstance();
        ContextInternal context = (ContextInternal)vertx.getOrCreateContext();

        SharedData sharedData = vertx.sharedData();
        LocalMap<String, Object> localMap = sharedData.getLocalMap("hao");
        JsonObject envConfig = (JsonObject)localMap.get("envConfig");
        JsonObject config = envConfig.getJsonObject("dataSource");

        jdbcPool = new JDBCPoolImpl(vertx, JDBCClientHolder.getJdbcClient(), context.tracer() == null ? null : new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, config.getString("jdbcUrl"), config.getString("username"), config.getString("database")));
    }
}
